import React, { useEffect, useState } from 'react'
import {
  BarsOutlined, ClockCircleOutlined, DeleteOutlined, EllipsisOutlined,
  FileDoneOutlined, FilterOutlined, PlusOutlined, ReloadOutlined, SearchOutlined,
  VerticalAlignBottomOutlined, VerticalAlignTopOutlined
} from '@ant-design/icons';
import { Pagination, Button, Flex, Input, Space, Form, Modal, Select, DatePicker, Table } from 'antd';
import type { TableColumnsType, PaginationProps } from 'antd';
import type { FormDataType } from '../utils/TS'
import Tables from '../components/Tables1';
import '../utils/Home.css'
import instance from '../axios/request'
import SelectChengyuan from '../components/SelectChengyuan'

// 新 增客户数据类型定义
interface CustomerDataType {
  key: string;
  customerName: string;
  customerTag: string;
  customerCategory: string;
  priceLevel: string;
  responsiblePerson: string;
}

// 新增表单数据类型定义
interface AddCustomerData {
  name: string;
  customerName: string;
  customerCode: string;
  DatePicker: Date | null;
  follow_type: string;
  follow_text: string;
  follow_name: string;
  salesDepartment: string;
}

const columns: TableColumnsType<FormDataType> = [
  {
    title: '',
    width: 0,
    dataIndex: 'id', // 隐藏列使用id
    key: 'id',
    fixed: 'left',
  },
  {
    title: '跟进内容记录',
    dataIndex: 'content',
    key: 'content',
    width: 120,
  },
  {
    title: '客户名称',
    dataIndex: ['custom', 'name'],
    key: 'name',
    width: 150,
  },
  {
    title: '客户编码',
    dataIndex: ['custom', 'code'],
    key: 'custom_id',
    width: 130,
  },
  {
    title: '跟进时间',
    dataIndex: 'follow_time',
    key: 'follow_time',
    width: 160,
  },
  {
    title: '跟进方式',
    dataIndex: 'follow_type',
    key: 'follow_type',
    width: 120,
  },
  {
    title: '跟进内容',
    dataIndex: 'follow_text',
    key: 'follow_text',
    width: 150,
  },
  {
    title: '跟进人',
    dataIndex: 'follow_name',
    key: 'follow_name',
    width: 100,
  },
  {
    title: '销售归属部门',
    dataIndex: 'follow_department',
    key: 'follow_department',
    width: 150,
  },
  {
    title: '提交人',
    dataIndex: 'sub_name',
    key: 'sub_name',
    width: 100,
  },
  {
    title: '提交时间',
    dataIndex: 'sub_time',
    key: 'sub_time',
    width: 160,
  },
  {
    title: '更新时间',
    dataIndex: 'up_time',
    key: 'up_time',
    width: 160,
  },
];

// 模拟客户数据，实际可从接口获取
const customerDataSource: CustomerDataType[] = [
  {
    key: '1',
    customerName: '帆软软件有限公司',
    customerTag: 'ME',
    customerCategory: '潜在客户',
    priceLevel: '一级售价',
    responsiblePerson: '张睿',
  },
  {
    key: '2',
    customerName: '示例：上海帆软',
    customerTag: 'KA',
    customerCategory: '战略合作',
    priceLevel: '二级售价',
    responsiblePerson: '张睿',
  },
  {
    key: '3',
    customerName: '示例：杭州帆软',
    customerTag: 'KA',
    customerCategory: '潜在客户',
    priceLevel: '一级售价',
    responsiblePerson: '张睿',
  },
  {
    key: '4',
    customerName: '示例：杭州简道云',
    customerTag: 'SMB',
    customerCategory: '潜在客户',
    priceLevel: '标准售价',
    responsiblePerson: '张睿',
  },
  {
    key: '5',
    customerName: '示例：无锡帆软',
    customerTag: 'KA',
    customerCategory: '成交客户',
    priceLevel: '二级售价',
    responsiblePerson: '张睿',
  },
  {
    key: '6',
    customerName: '示例：无锡简道云',
    customerTag: 'ME',
    customerCategory: '战略合作',
    priceLevel: '二级售价',
    responsiblePerson: '张睿',
  },
];

const customerColumns: TableColumnsType<CustomerDataType> = [
  {
    title: '',
    dataIndex: '',
    key: '',
    render: (_, record) => <Input type="radio" value={record.key} />,
  },
  { title: '客户名称', dataIndex: 'customerName', key: 'customerName' },
  { title: '客户标签', dataIndex: 'customerTag', key: 'customerTag' },
  { title: '客户分类', dataIndex: 'customerCategory', key: 'customerCategory' },
  { title: '价格等级', dataIndex: 'priceLevel', key: 'priceLevel' },
  { title: '负责人', dataIndex: 'responsiblePerson', key: 'responsiblePerson' },
];

export default function Home() {
  //表格数据
  const [dataSource, setdataSource] = useState<FormDataType[]>([])
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [form] = Form.useForm<AddCustomerData>(); // 用于管理表单数据
  // 新增选择客户的模态框状态
  const [isSelectCustomerModalOpen, setIsSelectCustomerModalOpen] = useState(false);
  // 用于存储选中的客户信息
  const [selectedCustomer, setSelectedCustomer] = useState<CustomerDataType | null>(null);
  const [len, setlen] = useState(0);
  const [current, setCurrent] = useState(1);
  const [pageSize, setPageSize] = useState(5); // 每页显示条数，可根据需求调整
  const [paginatedDataSource, setPaginatedDataSource] = useState<FormDataType[]>([]); // 分页后的数据

  const showModal = () => {
    setIsModalOpen(true);
    form.resetFields(); // 打开弹窗时重置表单
    setSelectedCustomer(null); // 清空选中的客户信息
  };

  // 打开选择客户模态框
  const showSelectCustomerModal = () => {
    setIsSelectCustomerModalOpen(true);
  };

  // 关闭选择客户模态框
  const handleSelectCustomerCancel = () => {
    setIsSelectCustomerModalOpen(false);
  };

  // 确认选择客户，这里简单演示直接取第一条选中数据，实际可根据 radio 选中逻辑处理
  const handleSelectCustomerOk = () => {
    // 实际应根据 radio 选中项获取对应客户数据，这里模拟选第一条
    const firstCustomer = customerDataSource[0];
    setSelectedCustomer(firstCustomer);
    form.setFieldsValue({
      customerName: firstCustomer.customerName,
      customerCode: firstCustomer.customerTag,
      salesDepartment: firstCustomer.responsiblePerson
    });
    setIsSelectCustomerModalOpen(false);
  };

  const getData = () => {
    instance.get('/Custom/follow').then(res => {
      console.log(res.data);
      setdataSource(res.data);
      setlen(res.data.length);
      // 初始化时进行第一次分页
      handlePagination(res.data, current, pageSize);
    });
  };

  const onChange: PaginationProps['onChange'] = (page) => {
    setCurrent(page);
    // 页码改变时重新分页
    handlePagination(dataSource, page, pageSize);
  };

  // 分页处理函数
  const handlePagination = (data: FormDataType[], currentPage: number, pageSize: number) => {
    const startIndex = (currentPage - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const newData = data.slice(startIndex, endIndex);
    setPaginatedDataSource(newData);
  };

  useEffect(() => {
    getData()
  }, [])

  // 处理表单提交
const handleSubmit = () => {
  form.validateFields().then(values => {
    // 格式化提交数据，匹配接口要求的字段
    const submitData = {
      code: selectedCustomer?.customerTag || '', // 客户编码（从选中客户获取）
      content: values.name || '', // 跟进内容记录
      custom_id: selectedCustomer?.key || '', // 客户ID（从选中客户获取）
      follow_department: values.salesDepartment || '', // 销售归属部门
      follow_name: values.follow_name || '', // 跟进人
      follow_text: values.follow_text || '', // 跟进内容
      follow_time: values.DatePicker?.format('YYYY/MM/DD HH:mm:ss') || '', // 跟进时间（格式化日期）
      follow_type: values.follow_type || '', // 跟进方式
      name: values.customerName || '' // 客户名称
    };

    // 调用接口添加跟进记录
    instance.post('/Custom/add_follow', submitData).then(res => {
      console.log('添加跟进记录成功:', res.data);
      // 刷新列表数据
      getData();
      setIsModalOpen(false);
    }).catch(error => {
      console.error('添加跟进记录失败:', error);
    });
  }).catch(errorInfo => {
    console.log('表单验证失败:', errorInfo);
  });
};

  return (
    <>
      <Flex className='topTit' justify={'space-between'}>
        <Flex>
          <Button color="green" variant="solid" icon={<PlusOutlined />} onClick={showModal}>添加</Button>
          <Button color="default" variant="link" icon={<VerticalAlignBottomOutlined />}>
            导入
          </Button>
          <Button color="default" variant="link" icon={<VerticalAlignTopOutlined />}>
            导出
          </Button>
          <Button color="default" variant="link" icon={<DeleteOutlined />}>
            删除
          </Button>
          <Button color="default" variant="link" icon={<ClockCircleOutlined />}>
            操作记录
          </Button>
        </Flex>
        <Flex>
          <Space.Compact size="large">
            <Input addonBefore={<SearchOutlined />} placeholder="large size" />
          </Space.Compact>
          <Button color="default" variant="link" icon={<FilterOutlined />}>
            操作记录
          </Button>
          <Button color="default" variant="link" icon={<FileDoneOutlined />} />
          <Button color="default" variant="link" icon={<BarsOutlined />} />
          <Button color="default" variant="link" icon={<ReloadOutlined />} />
          <Button color="default" variant="link" icon={<EllipsisOutlined />} />
        </Flex>
      </Flex>
      <Tables columns={columns} dataSource={paginatedDataSource} />
      <Pagination
        current={current}
        onChange={onChange}
        total={len}
        pageSize={pageSize} // 显示每页条数
        showSizeChanger // 显示每页条数切换器
        onShowSizeChange={(currentPage, newPageSize) => {
          setPageSize(newPageSize);
          handlePagination(dataSource, currentPage, newPageSize);
          setCurrent(currentPage);
        }}
      />
      <Modal
        title="跟进记录"
        closable={{ 'aria-label': 'Custom Close Button' }}
        open={isModalOpen}
        okText="提交"
        cancelText="取消"
        destroyOnHidden={true}
        width={'40%'}
        style={{ height: '80vh' }}
        onOk={handleSubmit}
        onCancel={() => setIsModalOpen(false)}
      >
        <div style={{ height: '70vh', overflowY: 'scroll' }}>
          <div className='wrapperStyle'>
            <div className='titleStyle'>客户跟进记录</div>
            <div className='underlineStyle'>
              <div className='solidUnderlineStyle'></div>
            </div>
          </div>
          <Form
            form={form}
            name="trigger1"
            style={{ maxWidth: 600 }}
            layout="vertical"
            autoComplete="off"
          >
            <Form.Item
              name="name"
              label="跟进内容记录"
              rules={[{ required: true }]}
            >
              <Input.TextArea rows={5} cols={20} />
            </Form.Item>
            <Flex justify={'space-around'}>
              <Form.Item label="选择客户">
                <Button
                  style={{ width: '280px' }}
                  type="dashed"
                  onClick={showSelectCustomerModal}
                  block
                  icon={<PlusOutlined />}
                >
                  选择数据
                </Button>
              </Form.Item>
              <Form.Item
                name="customerName"
                label="客户名称"
              >
                <Input
                  placeholder="暂无内容 "
                  disabled
                  style={{ width: '280px' }}
                />
              </Form.Item>
            </Flex>
            <Flex justify={'space-around'}>
              <Form.Item
                name="customerCode"
                label="客户编码"
              >
                <Input
                  placeholder="暂无内容"
                  disabled
                  style={{ width: '280px' }}
                />
              </Form.Item>
              <Form.Item
                label="跟进时间"
                name="DatePicker"
                rules={[{ required: true, message: 'Please input!' }]}
              >
                <DatePicker style={{ width: '280px' }} />
              </Form.Item>
            </Flex>
            <Flex justify={'space-around'}>
              <Form.Item
                name="follow_type"
                label="跟进方式"
                rules={[{ required: true }]}
              >
                <Select style={{ width: '280px' }}>
                  <Select.Option value="上门拜访">上门拜访</Select.Option>
                  <Select.Option value="电话拜访">电话拜访</Select.Option>
                  <Select.Option value="微信沟通">微信沟通</Select.Option>
                  <Select.Option value="其他">其他</Select.Option>
                </Select>
              </Form.Item>
              <Form.Item
                name="follow_text"
                label="跟进内容"
                rules={[{ required: true }]}
              >
                <Select style={{ width: '280px' }}>
                  <Select.Option value="初次沟通">初次沟通</Select.Option>
                  <Select.Option value="需求沟通">需求沟通</Select.Option>
                  <Select.Option value="方案确认">方案确认</Select.Option>
                  <Select.Option value="报价">报价</Select.Option>
                  <Select.Option value="合同签署">合同签署</Select.Option>
                  <Select.Option value="销售回访">销售回访</Select.Option>
                </Select>
              </Form.Item>
            </Flex>
            <Flex justify={'space-around'}>
              <Form.Item
                name="follow_name"
                label="跟进人"
              >
                <SelectChengyuan chengyuan={(value: any) => form.setFieldsValue({ follow_name: value })} />
              </Form.Item>
              <Form.Item
                name="salesDepartment"
                label="销售归属部门"
              >
                <Input
                  placeholder="暂无内容 "
                  disabled
                  style={{ width: '280px' }}
                />
              </Form.Item>
            </Flex>
          </Form>
        </div>
      </Modal>
      {/* 选择客户的模态框 */}
      <Modal
        title="选择数据"
        open={isSelectCustomerModalOpen}
        onOk={handleSelectCustomerOk}
        onCancel={handleSelectCustomerCancel}
        okText="确认选择"
        cancelText="取消"
        width={'60%'}
      >
        <div style={{ height: '50vh', overflowY: 'auto' }}>
          <Table
            columns={customerColumns}
            dataSource={customerDataSource}
            rowKey="key"
            pagination={{ pageSize: 10 }}
          />
        </div>
      </Modal>
    </>
  )
}